package org.edu.modules.stu.biye.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.base.ConditionDto;
import org.edu.common.dto.ExcelPo;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.common.utils.PoiUtils;
import org.edu.modules.stu.base.dto.VeBaseStudentGraduationDto;
import org.edu.modules.stu.base.service.VeBaseStudentService;
import org.edu.modules.stu.biye.dto.VeStuGraduationAuditInfoDto;
import org.edu.common.dto.AllDto;
import org.edu.modules.stu.biye.entity.VeStuGraduationAuditInfo;
import org.edu.modules.stu.biye.service.VeStuGraduationAuditInfoService;
import org.edu.common.api.vo.Result;
import org.edu.common.base.PageDto;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.edu.modules.stu.common.service.VeBaseTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

@Api(tags = {"毕业审核信息"})
@RestController
@RequestMapping("/stu/veStuGraduationAuditInfo")
@Slf4j
public class VeStuGraduationAuditInfoController {

    @Autowired
    private VeStuGraduationAuditInfoService veStuGraduationAuditInfoService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Autowired
    private VeBaseTeacherService veBaseTeacherService;

    @Autowired
    private VeBaseStudentService veBaseStudentService;


    @ApiOperation("班主任审核列表")
    @PostMapping("/listByBZR")
    public Result<?> listByBZR(@RequestBody PageDto<VeBaseStudentGraduationDto> page) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        IPage<VeStuGraduationAuditInfoDto> pageDto = null;
        //如果用户类型是1，为教师账号
        Integer auditStatus = -1;
        //获取参数
        ListIterator<ConditionDto> iterator = page.getConditions().listIterator();
        while (iterator.hasNext()) {
            int currentIndex = iterator.nextIndex();
            // 获取当前行（元素）
            ConditionDto currentCondition = iterator.next();
            // 处理当前元素
            if (page.getConditions().get(currentIndex).getColumn().equals("audit_status") == true) {
                auditStatus = (Integer) currentCondition.getValue();
                if (auditStatus == -1) {
                    //待审核
                    QueryWrapper<VeStuGraduationAuditInfoDto> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("xsdqztm", "ZX");
                    if (appUser.getUserType().contains("1")) {
                        //如果用户类型是1，为教师账号,查班主任
                        List<Integer> bjIdsList = veBaseTeacherService.listGraduationByTeacherId(appUser.getUserId());
                        queryWrapper.in("bj_id", bjIdsList);
                    }
                    pageDto = veBaseStudentService.pageGraduationDto(page, queryWrapper);

                    pageDto.getRecords().forEach(item ->
                    {
                        if (item.getAuditStatus()==null) {
                            item.setAuditStatus(-1);
                        }
                    });
                    return Result.OK(pageDto);
                } else {
                    //0不通过，1通过
                    QueryWrapper<VeStuGraduationAuditInfoDto> queryWrapper = page.buildQueryWrapper(VeStuGraduationAuditInfoDto.class);
                    queryWrapper.eq("audit_type", "BZR");
                    if (appUser.getUserType().contains("1")) {
                        queryWrapper.eq("createUserId", appUser.getUserId());
                    }
                    pageDto = veStuGraduationAuditInfoService.pageDto(page, queryWrapper);
                    return Result.OK(pageDto);
                }
            }
        }
        return Result.OK(pageDto);
    }

    @ApiOperation("分页查询毕业审核信息")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageDto<VeStuGraduationAuditInfo> page) {
        QueryWrapper<VeStuGraduationAuditInfo> queryWrapper = page.buildQueryWrapper(VeStuGraduationAuditInfo.class);
        IPage<VeStuGraduationAuditInfoDto> pageDto = veStuGraduationAuditInfoService.pageDto(page, queryWrapper);
        return Result.OK(pageDto);
    }

    /**
     * 查询所有
     */
    @ApiOperation("查询所有")
    @PostMapping("/all")
    public Result<?> all(@RequestBody AllDto<VeStuGraduationAuditInfo> page) {
        QueryWrapper<VeStuGraduationAuditInfo> queryWrapper = page.buildQueryWrapper(VeStuGraduationAuditInfo.class);
        List<VeStuGraduationAuditInfo> list = veStuGraduationAuditInfoService.listByWrapper(queryWrapper);
        return Result.OK(list);
    }


    @ApiOperation("导出数据）")
    @PostMapping("/export")
    public Result<?> export(@RequestBody PageDto<VeStuGraduationAuditInfo> page, HttpServletResponse resp) {
        QueryWrapper<VeStuGraduationAuditInfo> queryWrapper = page.buildQueryWrapper(VeStuGraduationAuditInfo.class);
        List<ExcelPo> list = new ArrayList<>();
        list.add(new ExcelPo("学生Id", "stuId"));
        list.add(new ExcelPo("审核类型(BZR=>班主任，CJ=>成绩（学分），CW=>财务，XSC=>学生处)", "auditType"));
        list.add(new ExcelPo("审核状态(0不通过，1通过，-1待审核）", "auditStatus"));
        list.add(new ExcelPo("备注/班主任评语", "remark"));
        list.add(new ExcelPo("创建人ID", "createuserid"));
        list.add(new ExcelPo("终端ID", "terminalid"));
        PoiUtils.downloadFile(resp, veStuGraduationAuditInfoService.page(page, queryWrapper).getRecords(), list);
        return Result.OK();
    }

    @AutoLog(value = "毕业审核信息-分页列表查询")
    @ApiOperation(value = "毕业审核信息-分页列表查询", notes = "毕业审核信息-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(VeStuGraduationAuditInfo entity,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeStuGraduationAuditInfo> queryWrapper = QueryGenerator.initQueryWrapper(entity, req.getParameterMap());
        PageDto<VeStuGraduationAuditInfo> page = new PageDto<VeStuGraduationAuditInfo>(pageNo, pageSize);
        IPage<VeStuGraduationAuditInfo> pageList = veStuGraduationAuditInfoService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeStuGraduationAuditInfo dto = veStuGraduationAuditInfoService.findDtoById(id);
        if (dto == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dto);
    }

    @AutoLog(value = "添加")
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeStuGraduationAuditInfoDto dto) {
        veStuGraduationAuditInfoService.insertOrUpdate(dto, true);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeStuGraduationAuditInfoDto dto) {
        veStuGraduationAuditInfoService.insertOrUpdate(dto, false);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        veStuGraduationAuditInfoService.delete(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "班主任审核")
    @ApiOperation(value = "班主任审核")
    @PostMapping(value = "/auditByBZR")
    public Result<?> auditByBZR(@RequestBody VeStuGraduationAuditInfoDto dto) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        dto.setCreateuserid(appUser.getUserId());
        veStuGraduationAuditInfoService.auditByBZR(dto);
        return Result.OK("更新成功!");
    }

    @AutoLog(value = "更新状态")
    @ApiOperation(value = "更新状态")
    @PostMapping(value = "/updateStatus")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateStatus(@RequestBody VeStuGraduationAuditInfoDto statusDto) {
        LambdaUpdateWrapper<VeStuGraduationAuditInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(VeStuGraduationAuditInfo::getAuditStatus, statusDto.getAuditStatus());
        updateWrapper.set(VeStuGraduationAuditInfo::getRemark, statusDto.getRemark());
        updateWrapper.eq(VeStuGraduationAuditInfo::getId, statusDto.getId());
        veStuGraduationAuditInfoService.update(updateWrapper);
        veStuGraduationAuditInfoService.insertGraduatedStudent(statusDto.getStuId());
        return Result.OK("更新成功!");
    }


}
